package cn.wanho.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

public class QiniuUtil {

    static String accessKey = "B2XUZcKPMGaGWWazDGIueFBtgqXWKjasj6i_eH4O";
    static String secretKey = "WuPvGC64RnxHjg_SOAsQuwW-J2pbav4KYXdGCxSH";
    static String bucket = "wanhocms";
    private static Auth auth;
    private static UploadManager uploadManager;
    private static String key = null;

    static {
        //构造一个带指定 Region 对象的配置类
        Zone z = Zone.autoZone();
        Configuration cfg = new Configuration(z);
//...其他参数参考类注释
         uploadManager = new UploadManager(cfg);
        auth = Auth.create(accessKey, secretKey);
    }

    /**
     * 七牛云文件上传
     * @param uploadBytes  修改成字节数组
     */
    public static String upload(byte[] uploadBytes){
        String upToken = auth.uploadToken(bucket);
        Response response = null;
        DefaultPutRet putRet = null;
        try {
             response = uploadManager.put(uploadBytes, key, upToken);
            //解析上传成功的结果
             putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
            return putRet.hash;


    }

    /**
     * 下载地址暴露
     * @return URL 私有空间真实地址
     */
    public static String download(String URL) {
        //调用privateDownloadUrl方法生成下载链接,第二个参数可以设置Token的过期时间
        String downloadRUL = auth.privateDownloadUrl(URL, 3600);
       return downloadRUL;
    }

    public static void main(String[] args) {
      //  QiniuUtil.upload("/Users/jianma/Downloads/e883e20af3be4223a8cae2db5fcb85dc.jpeg");

      //  System.out.println(QiniuUtil.download("https://file.majian1210.cn/FkYOaHQNpE6PO-FKcA21Ul6K_wJO"));
    }
}

